package com.seguriapp.common.security;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

import com.google.common.collect.Lists;
import com.seguriapp.entities.User;
import com.seguriapp.service.LoginService;
import com.seguriapp.service.ValidateCredentialsRequest;
import com.seguriapp.service.ValidateCredentialsResponse;
import com.seguriapp.util.Util;

public class SeguriAppAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

  private static final Logger LOGGER = Logger.getLogger(SeguriAppAuthenticationProvider.class);

  private final LoginService loginService;

  public SeguriAppAuthenticationProvider(final LoginService loginService) {
    this.loginService = loginService;
  }

  @Override
  protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken token) throws AuthenticationException {
    // TODO Auto-generated method stub
  }

  @Override
  protected UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken token) throws AuthenticationException {
    final ValidateCredentialsRequest request = new ValidateCredentialsRequest();
    request.setUsername(username);
    request.setPassword((String) token.getCredentials());
    final ValidateCredentialsResponse response = loginService.validateCredentials(request);
    LOGGER.info("Login USUARIO : " + username);
    final User user = new User(response.getUserId(), username, response.isAdministrator(), response.getLastDateLoggedIn(), response.getEntitiesList());
    final SeguriAppSession session = new SeguriAppSession();
    session.put(SeguriAppSession.Key.User, user);
    session.put(SeguriAppSession.Key.MenuLinks, (Serializable) response.getMenuList());
    return new SeguriAppUser(username, username, getAuthoritiesList(), session);
  }

  private Collection<GrantedAuthority> getAuthoritiesList() {
    final List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
    grantedAuthorities.add(new GrantedAuthorityImpl(Util.ROLE_BY_DEFECT));
    return grantedAuthorities;
  }

}
